package com.xnck.mfpms.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("test")
public class TestController {

    @RequestMapping(value = "default",method = RequestMethod.GET)
    public ModelAndView getTest() {
        ModelAndView mv = new ModelAndView("test");
        mv.addObject("start", true);
        return mv;
    }

    @RequestMapping(value = "default", method = RequestMethod.POST)
    public ModelAndView postTest(@RequestParam(value = "count", required = false)Integer count,
                                 @RequestParam(value = "result", required = false)Integer result) {
        count = null == count ? 0 : count;
        result = null == result ? 0 : result;
        ModelAndView mv = new ModelAndView("test");
        mv.addObject("start", false);
        List<String> results = crateResult(count, result);
        mv.addObject("results", results);
        return mv;
    }

    private List<String> crateResult(int count, int maxResult) {
        if (0 == count || 0 == maxResult) {
            return new ArrayList<String>();
        }
        int startNum = 0, endNum = maxResult;
        List<String> results = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            int flag = new Random().nextInt(2);
            if (0 == flag) {
                String additive = createAdditive(startNum, endNum, maxResult);
                results.add(additive);
            } else {
                String Subtraction = createSubtraction(startNum, endNum);
                results.add(Subtraction);
            }
        }
        return results;
    }

    private String createAdditive(int startNum, int endNum, int maxResult) {
        int first = new Random().nextInt(endNum - startNum + 1) + startNum;
        int newEndNum = maxResult - first;
        int second = new Random().nextInt(newEndNum - startNum + 1) + startNum;
        return first + " + " + second + " = ";
    }

    private String createSubtraction(int startNum, int endNum) {
        int first = new Random().nextInt(endNum - startNum + 1) + startNum;
        int second = new Random().nextInt(first - startNum + 1) + startNum;
        return first + " - " + second + " = ";
    }
}
